<template>
  <view class="app-layout">
    <!-- <app-header></app-header> -->
    <view class="app-main">
      <app-sider pageKey="takeOrder"></app-sider>
      <view class="app-content">
        <view class="take-wrapper">
          <view class="take-left">
            <view class="member-section">
              <text class="section-title">会员用户</text>

              <view v-if="isSearchMode" class="member-content search-mode">
                <view class="search-row">
                  <!-- @search="handleSearch" @clear="handleReset" -->
                  <u-search class="search-input" :disabled="true" @click="handleSearchVip" placeholder="搜索会员"
                    v-model="phone" clearable bgColor="#fff" borderColor="#e5e5e5" :showAction="false"></u-search>
                  <view class="scan-btn" @click="handleScan">
                    <u-icon name="scan" size="24" color="#0F90FD"></u-icon>
                    <text class="scan-text">扫码</text>
                  </view>
                </view>
                <view class="dining-row">
                  <text class="dining-label">就餐方式：</text>
                  <u-radio-group v-model="dining" placement="column">
                    <u-radio label="自提" name="自提">
                    </u-radio>
                  </u-radio-group>
                </view>
              </view>
              <view v-else class="member-content result-mode">
                <view>
                  <view class="result-row">
                    <view class="left-group">
                      <image class="avatar" src="../../static/imgs/avatar.png"></image>
                      <view class="user-text">
                        <text class="user-name">{{userInfo.userName}}</text>
                        <text class="user-phone">{{userInfo.phonenumber}}</text>
                      </view>
                    </view>

                    <view class="right-group">
                      <view class="member-tag">xx会员</view>
                      <view class="point-group">
                        <image class="point-icon" src="../../static/imgs/order1.png"></image>
                        <text class="point-text">-</text>
                      </view>

                    </view>
                  </view>

                  <!-- 底部：就餐方式 -->
                  <view class="bottom-group">
                    <view class="dining-row">
                      <text class="dining-label">就餐方式：</text>
                      <u-radio-group v-model="dining" placement="column">
                        <u-radio label="自提" name="自提">
                        </u-radio>
                      </u-radio-group>

                    </view>
                    <image class="arrow-icon" src="../../static/imgs/order2.png" @click="checkVip"></image>
                  </view>
                </view>
              </view>
            </view>

            <view class="order-detail-wrapper">
              <view class="selected-header">
                <text class="selected-title">已选商品</text>
                <view class="clear-btn" @click="handleClear">
                  <u-icon name="trash" size="16" color="#333333"></u-icon>
                  <text class="clear-text">清空</text>
                </view>
              </view>

              <view class="empty-box" v-if="detailList.length<=0">
                <image src="/src/static/imgs/empty.png" mode="widthFix" style="width: 80px;"></image>
                <view class="text1" style="color: #999;">还没有商品，请加购商品~</view>
              </view>
              <scroll-view scroll-y="true" ref="scrollView" style="flex: 1; overflow: auto"
                @scrolltolower="onScrollToLower" v-else>
                <view class="goods-container">
                  <u-swipe-action :auto-close="true">
                    <!-- 遍历所有商品项 -->
                    <template v-for="(item, parentIndex) in detailList">
                      <!-- 1. 套餐项（带children） -->
                      <view v-if="item.children && item.children.length" :key="`package-${item.name}`">
                        <!-- 套餐标题 -->
                        <u-swipe-action-item :name="parentIndex" :options="deleteOption" @click="onSwipeBtnClick">
                          <view class="combo-item">
                            <view class="package-title">{{ item.name }}</view>
                            <view class="goods-items" v-for="(child, childIndex) in item.children" :key="child.id">
                              <view class="top-row">
                                <image :src="child.image" mode="aspectFill" class="goods-img"></image>
                                <view class="text-row">
                                  <text class="goods-name">{{ child.name }}</text>
                                  <text class="goods-spec">{{ child.spec }}</text>
                                </view>
                              </view>
                              <view class="bottom-row">
                                <text class="price">¥{{ child.totalPrice }}</text>
                                <view class="quantity-box">
                                  <u-number-box :min="1" v-model="child.quantity" @plus="() => handlePlus(child)"
                                    @minus="() => handleMinus(child)" :buttonWidth="20" :buttonSize="20"
                                    buttonRadius="50%" bgColor="#fff"></u-number-box>
                                </view>
                              </view>
                            </view>
                          </view>
                        </u-swipe-action-item>
                      </view>

                      <!-- 2. 单品项（无children） -->
                      <u-swipe-action-item v-else :key="item.id" :name="parentIndex" :options="deleteOption"
                        @click="onSwipeBtnClick">
                        <view class="goods-item">
                          <view class="top-row">
                            <image :src="item.spuImage" mode="aspectFill" class="goods-img"></image>
                            <view class="text-row">
                              <text class="goods-name">{{ item.spuName }}</text>
                              <text class="goods-spec">{{ item.productCombo }}</text>
                            </view>
                          </view>
                          <view class="bottom-row">
                            <text class="price">¥{{ item.totalPrice }}</text>
                            <view class="quantity-box">
                              <u-number-box :min="1" :max="999" v-model="item.quantity" @plus="() => handlePlus(item)"
                                @minus="() => handleMinus(item)" @blur="() => handleBlur(item)" :buttonWidth="20"
                                :buttonSize="20" buttonRadius="50%" bgColor="#fff"></u-number-box>
                            </view>
                          </view>
                        </view>
                      </u-swipe-action-item>
                    </template>
                  </u-swipe-action>
                </view>
              </scroll-view>
              <view class="detail-foot">
                <view class="foot-info">商品合计：<text>{{totalNum}}</text> 件</view>
                <view class="foot-info">合计金额：<text>￥{{totalPrice}}</text></view>

              </view>
            </view>
          </view>
          <view class="goods-list-wrapper">
            <view class="order-search">
              <view class="flex-row" style=" margin-bottom:12px;">
                <u-search placeholder="请输入商品ID/名称" v-model="pageInfo.keyword" clearable bgColor="#fff"
                  borderColor="#e5e5e5" :showAction="false" @search="handleSearch" @clear="handleReset"></u-search>

                <view class="flex-row">
                  <u-button type="primary" text="搜索" @click="handleSearch"></u-button>
                </view>
              </view>

              <scroll-view scroll-x="true">
                <view class="type-list">
                  <view v-for="(tab, index) in tabType" :key="index" class="type-item"
                    :class="{ activeType: currentSelectedId == tab.categoryId  }" @click="handlecurrentTabType(tab)">
                    {{ tab.categoryName }}
                  </view>
                </view>
              </scroll-view>
            </view>

            <view class="" style="margin-right: 10px; flex: 1; overflow: hidden;">
              <scroll-view scroll-y="true" ref="scrollView" style="height: 100%" @scrolltolower="onScrollToLower"
                v-if="goodsList.length > 0">

                <view class="goods-grid">
                  <view class="goods-item" :class="{'sold-out':item.isPublished == 0||item.totalStock==0}"
                    v-for="(item, index) in goodsList" :key="index" @click="handleDetail(item)">
                    <view class="status-tag" :class="{
                                  'off-sale': item.isPublished === 0,
                                  'on-sale': item.isPublished === 1,
                                }" v-if="item.totalStock != 0">
                      {{ item.isPublished === 0 ? '下架' : '在售' }}
                    </view>
                    <view class="sold-out-mask" v-if="item.totalStock === 0">
                      <image src="../../static/imgs/sell.png" mode="scaleToFill"></image>
                    </view>

                    <image class="goods-img" :src="item.mainImage" mode="aspectFill" @error="onImageError"></image>

                    <view class="goods-info">
                      <view class="goods-infoi-top">
                        <text class="goods-name">{{ item.name }}</text>
                        <text class="goods-type">限量</text>
                      </view>
                      <view class="stock-price">
                        <text class="stock"> 库存{{ item.totalStock }} </text>
                        <text class="price" v-if="item.totalStock != 0">¥{{ item.lowestPrice }}</text>
                      </view>
                    </view>
                  </view>
                </view>

              </scroll-view>

              <view class="empty-box" v-if="goodsList.length <=0">
                <image src="/src/static/imgs/emptyW.png" mode="widthFix" style="width: 240px;"></image>
                <view class="text1" style="color: #999;">暂无数据</view>
              </view>
            </view>
            <view class="detail-foot">
              <view class="foot-btn" style="margin: auto">
                <view class="order-btn" :class="{'out':detailList.length<=0}" @click="handleOrderNotes">订单备注</view>
                <view class="order-btn" :class="{'out':detailList.length<=0}" @click="handleAdd">提交订单</view>
              </view>
            </view>
          </view>
        </view>

      </view>
    </view>
    <!-- 规格 -->
    <detailPopup :showPopup="showdetailPopup" v-if="showdetailPopup" :phone="phone" :spuId="spuId"
      @closePopup="closePopup" @addCart="addCart" />
    <!-- 会员 -->
    <memberPopup :showPopup="showmemberPopup" v-if="showmemberPopup" :spuId="spuId" @closePopup="closememberPopup"
      @sureSearch="sureSearch" />
    <!-- 提交 -->
    <submitPopup :showPopup="showsubPopup" v-if="showsubPopup" :totalPrices="totalPrice" @closesubPopup="closesubPopup"
      @sureHarvest="sureHarvest" />
  </view>
  <!-- 订单备注 -->
  <u-popup v-if="showRemarks" :show="showRemarks" @close="cancelRemarks" :round="10" mode="center">
    <view class="popup-con">
      <view class="applyfor-tit">
        订单备注
      </view>
      <view class="applyfor-info">
        <u-textarea v-model="remarks" placeholder="请输入" count :maxlength="30" :auto-height="false"
          :showConfirmBar="false" :adjustPosition="false"></u-textarea>
      </view>
      <view class="button-group">
        <button class="cancel-btn" @click="cancelRemarks">取消</button>
        <button class="pay-btn" @click="sureRemarks">确定提交</button>
      </view>
    </view>
  </u-popup>
  <!-- 现金支付 -->
  <u-popup v-if="showPayment" :show="showPayment" @close="cancelPayment" :round="10" mode="center">
    <view class="popup-con">
      <view class="applyfor-tit">
        收款支付
      </view>
      <view class="applyfor-info">
        <view class="applyfor-title">
          应付金额：￥{{totalPrice}}
        </view>
        <view class="applyfor-item">
          <view class="applyfor-label">
            <text>*</text>
            收款现金
          </view>
          <uni-easyinput v-model="cashreceived" placeholder="请输入收款金额" type="digit" clearable></uni-easyinput>
        </view>
        <view class="applyfor-item">
          <view class="applyfor-label">
            备注
          </view>
          <uni-easyinput placeholder="请输入" type="text" clearable v-model="remarksPayment"></uni-easyinput>
        </view>
      </view>
      <view class="button-group">
        <button class="cancel-btn" @click="cancelPayment">取消</button>
        <button class="pay-btn" @click="surePayment">确定</button>
      </view>
    </view>
  </u-popup>
</template>
<script setup>
  import {
    ref,
    computed,
    nextTick,
    reactive,
  } from 'vue'
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  import {
    productPage,
    getTreeCategory
  } from '@/requests/apis/products'
  import {
    updateCart,
    getCartList,
    verifyPhone,
    clearCart,
    createOrder,
    purchaseByCash,
    barcodePayment,
    deleteOrder
  } from '@/requests/apis/takeOrder'
  import {
    useScanStore
  } from '@/stores/modules/scan';
  const scanStore = useScanStore()
  import detailPopup from './component/detail-popup.vue'
  import memberPopup from './component/member-popup.vue'
  import submitPopup from './component/submit-popup.vue'
  let showdetailPopup = ref(false)
  let showmemberPopup = ref(false)
  let showsubPopup = ref(false)
  let showRemarks = ref(false)
  let showPayment = ref(false)
  let cashreceived = ref() //收款现金
  let remarksPayment = ref() //收款现金备注
  let amountPayable = ref(487) //应付金额
  let remarks = ref()
  let isClicked = ref(false)
  let spuId = ref()
  let quantity = ref()
  let dining = ref('自提')
  let isSearchMode = ref(true)
  let phone = ref()
  let userInfo = ref({})
  let pageInfo = reactive({
    total: 0,
    page: 1,
    limit: 20,
    keyword: '',
    categoryIds: undefined
  });
  let currentSelectedId = ref(-1)
  let tabType = ref([])
  const goodsList = ref([])
  let isMergeRequest = false;
  const isScanning = ref(false); // 标记：是否正在扫码中
  let orderId = ref()
  const detailList = ref([
    // {
    //   name: "套餐名称",
    //   children: [{
    //       id: 3,
    //       name: '桑葚莓莓(升级版)',
    //       spec: '正常冰，正常糖，西柚粒*1，玫果冻*2',
    //       price: 17.00,
    //       image: 'https://hongwu-1318589231.cos.ap-guangzhou.myqcloud.com/sass/default/2025/08/22/8b5e0abe70f94ee2a23d2914f09c8002FFBK6d98hhc9adad8bea6820460be429eee2110b89ab.png',
    //       quantity: 1
    //     },
    //     {
    //       id: 4,
    //       name: '桑葚莓莓(升级版)',
    //       spec: '正常冰，正常糖，西柚粒*1，玫果冻*2',
    //       price: 17.00,
    //       image: 'https://hongwu-1318589231.cos.ap-guangzhou.myqcloud.com/sass/default/2025/08/22/8b5e0abe70f94ee2a23d2914f09c8002FFBK6d98hhc9adad8bea6820460be429eee2110b89ab.png',
    //       quantity: 1
    //     },
    //   ]
    // }, {
    //   id: 1,
    //   name: '桑葚莓莓(升级版)',
    //   spec: '正常冰，正常糖，西柚粒*1，玫果冻*2',
    //   price: 17.00,
    //   image: 'https://hongwu-1318589231.cos.ap-guangzhou.myqcloud.com/sass/default/2025/08/22/8b5e0abe70f94ee2a23d2914f09c8002FFBK6d98hhc9adad8bea6820460be429eee2110b89ab.png',
    //   quantity: 1
    // },
    // {
    //   id: 2,
    //   name: '桑葚莓莓(升级版)',
    //   spec: '商品规格，属性，加料',
    //   price: 17.00,
    //   image: 'https://hongwu-1318589231.cos.ap-guangzhou.myqcloud.com/sass/default/2025/08/22/8b5e0abe70f94ee2a23d2914f09c8002FFBK6d98hhc9adad8bea6820460be429eee2110b89ab.png', // 占位图
    //   quantity: 2
    // }
  ]);
  const deleteOption = ref([{
    text: '删除', // 按钮文字
    style: { // 按钮样式
      backgroundColor: '#FF5D4E', // 红色背景
      color: '#fff', // 白色文字
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center'
    }
  }]);
  onLoad(() => {
    // plus.screen.lockOrientation('landscape-primary')
  })
  onShow(async () => {
    // #ifdef APP-PLUS
    uni.hideTabBar()
    // #endif
    console.log("进这里不")
    pageInfo.categoryIds = undefined
    if (!isScanning.value) {
      console.log('非扫码场景，执行正常onShow逻辑');
      getMerge()
      getCategoryList()
      return;
    }
  })
  const getMerge = () => {
    const prevPage = pageInfo.page;
    if (prevPage !== 1) {
      isMergeRequest = true;
      pageInfo.limit = prevPage * 20;
      pageInfo.page = 1;
      getproductPage('merge');
    } else {
      pageInfo.page = 1;
      pageInfo.limit = 20;
      getproductPage();
    }
  };
  const getCategoryList = async () => {
    let res = await getTreeCategory({
      isActive: 1
    })
    let arr = res.Result || []
    arr.unshift({
      categoryName: '全部',
      categoryId: -1,
      children: [],
    })
    tabType.value = arr
  }
  const checkVip = () => {
    isSearchMode.value = !isSearchMode.value
    remarks.value = ""
    phone.value = ""
    isClicked.value = false
    if (detailList.value.length > 0) {
      detailList.value = []
      clearCart({
        phone: phone.value
      }).then((res) => {
        uni.hideLoading();
        if (res.ResponseCode == 1) {
          getCartListFun()
          phone.value = ''
        }
      })
    }
  }
  const handleScan = () => {
    uni.showToast({
      title: '正在开发中',
      icon: 'none',
    })
  }
  const getproductPage = async (type) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    try {
      let res = await productPage({
        ...pageInfo,
      })
      pageInfo.total = res.Result.total
      if (type === 'merge') {
        goodsList.value = res.Result.records || [];
        pageInfo.page = Math.ceil(goodsList.value.length / 20);
        pageInfo.limit = 20;
        isMergeRequest = false;
      } else if (type === 'add') {
        goodsList.value = [...goodsList.value, ...(res.Result.records || [])];
      } else {
        goodsList.value = res.Result.records || [];
      }
    } catch (error) {
      console.log(error);
      uni.hideLoading();
    } finally {
      uni.hideLoading();
    }

  }
  const handleSearch = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    getproductPage()
  }
  const handleReset = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.keyword = ''
    getproductPage()
  }
  const handlecurrentTabType = (item) => {
    console.log(item, '1111111111')
    let ids = [];
    if (item.categoryId == -1) {
      pageInfo.categoryIds = undefined
    } else {
      if (item.children && item.children.length > 0) {
        item.children.forEach(child => {
          ids.push(child.categoryId);
        });
      } else {
        ids = [item.categoryId]
      }
      pageInfo.categoryIds = ids
    }

    console.log(ids, 'ids')
    pageInfo.limit = 20;
    pageInfo.page = 1;
    currentSelectedId.value = item.categoryId;
    getproductPage()
  }
  const getCartListFun = async () => {
    let fun = phone.value ? {
      phone: phone.value,
      sceneCode: "pickup"
    } : {
      sceneCode: "pickup"
    }
    let carRes = await getCartList({
      phone: phone.value ? phone.value : '',
      sceneCode: "pickup"
    });
    detailList.value = carRes.Result.items;
  }
  const totalNum = computed(() => {
    return detailList.value.reduce((sum, item) => sum + item.quantity, 0);
  });

  // 2. 商品总价
  const totalPrice = computed(() => {
    const totalCent = detailList.value.reduce((sum, item) => {
      return sum + Math.round(item.totalPrice * 100);
    }, 0);
    return totalCent / 100;
  });
  // 增加数量
  const handlePlus = async (item) => {
    const oldValue = Number(item.quantity);
    const newValue = oldValue + 1;
    if (newValue <= item.stock) {
      item.quantity = newValue;
      // item.totalPrice = item.totalPrice * newValue;
      await updateCart({
        cartItemId: item.cartItemId,
        quantity: item.quantity
      })
      getCartListFun()
    } else {
      uni.showToast({
        title: '商品数量已到达库存数量',
        icon: 'none'
      })
    }
  };
  // 处理减号点击事件
  const handleMinus = async (item) => {
    const oldValue = Number(item.quantity);
    const newValue = oldValue - 1;
    if (newValue > 0) {
      item.quantity = newValue;
      await updateCart({
        cartItemId: item.cartItemId,
        quantity: item.quantity
      })
      getCartListFun()

    }
  }
  const handleBlur = async (item) => {
    const oldValue = Number(item.quantity);
    const newValue = oldValue + 1;
    if (newValue <= item.stock) {
      item.quantity = newValue;
      await updateCart({
        cartItemId: item.cartItemId,
        quantity: item.quantity
      })
      getCartListFun()
    } else {
      uni.showToast({
        title: `库存紧张,当前商品规格,[${item.specDesc}]仅剩${item.stock}件`,
        icon: 'none'
      })
      await updateCart({
        cartItemId: item.cartItemId,
        quantity: item.stock
      })
      getCartListFun()
    }
  }
  // 清空购物车
  const handleClear = async () => {
    uni.showLoading({
      title: '处理中',
      mask: true
    })
    clearCart({
      phone: phone.value ? phone.value : '',
    }).then((res) => {
      uni.hideLoading();
      if (res.ResponseCode == 1) {
        uni.showToast({
          title: '清空成功'
        });
        getCartListFun()
      }
    })
  }
  const onSwipeBtnClick = (prop) => {
    console.log(prop, '11111111')
    if (prop.index === 0) {
      let obj = detailList.value[prop.name];
      updateCart({
        cartItemId: obj.cartItemId,
        quantity: 0
      }).then((res) => {
        uni.showToast({
          title: '删除成功'
        });
        getCartListFun()
      })
    }
  };
  // 点击规格详情
  const handleDetail = (item) => {
    if (item.isPublished == 0 || item.totalStock == 0) {
      return
    }
    showdetailPopup.value = true;
    spuId.value = item.spuId
  }

  // 规格详情加购成功
  const addCart = async (valuename) => {
    showdetailPopup.value = false;
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    getCartListFun()
    uni.hideLoading();
  };
  // 关闭规格详情
  const closePopup = () => {
    showdetailPopup.value = false;
  }
  // 点击会员搜索
  const handleSearchVip = () => {
    phone.value = ''
    showmemberPopup.value = true;
  }
  // 会员搜索
  const sureSearch = (phoneNumber) => {
    console.log(phoneNumber, 'phoneNumber')
    phone.value = phoneNumber
    showmemberPopup.value = false;
    verifyPhone({
      phone: phoneNumber
    }).then((res) => {
      console.log(res, 'res？')
      if (res.ResponseCode == 1) {

        userInfo.value = res.Result
        isSearchMode.value = false
      }
    })
  }
  // 关闭会员
  const closememberPopup = () => {
    showmemberPopup.value = false;
  }
  //订单备注
  const handleOrderNotes = () => {
    if (detailList.value.length <= 0) {
      return
    }
    showRemarks.value = true
  }
  // 关闭订单备注
  const cancelRemarks = () => {
    showRemarks.value = false
    // remarks.value = ''
    if (!isClicked.value) {
      remarks.value = ''
    }
  }
  // 确认提交订单备注
  const sureRemarks = () => {
    showRemarks.value = false
    isClicked.value = true;
  }

  // 提交订单
  const handleAdd = () => {
    if (detailList.value.length <= 0) {
      return
    }
    showsubPopup.value = true
  }
  // 确认收款
  const sureHarvest = (type) => {
    showsubPopup.value = false;
    console.log(userInfo.value, 'userInfo.value')
    if (type == 'cash') {
      showPayment.value = true;
    } else {
      startScan()
    }

  }
  // 关闭提交订单弹窗
  const closesubPopup = () => {
    showsubPopup.value = false
  }

  // 关闭现金支付
  const cancelPayment = () => {
    showPayment.value = false;
    cashreceived.value = ''
    remarksPayment.value = ''
  }
  // 开始扫码
  const startScan = async () => {
    uni.showLoading({
      title: '创建订单中',
      mask: true
    });
    let checked = detailList.value.map(item => {
      return item.cartItemId;
    });

    const _res = await createOrder({
      sceneCode: "pickup",
      source: phone.value ? 1 : 2,
      remark: remarks.value,
      cartItemIds: checked,
      userId: userInfo.value ?
        userInfo.value.userId : ''
    })
    if (_res.Result) {
      orderId.value = _res.Result
      isScanning.value = true;
      scanStore.reset();
      uni.scanCode({
        scanType: ['qrCode'],
        onlyFromCamera: true,
        autoDecodeCharset: true,
        // 扫码成功（拿到付款码后立即处理支付）
        success: async (res) => {
          try {
            // 1. 校验付款码格式（必须是18位数字）
            const payCode = res.result.trim();
            if (!/^\d{18}$/.test(payCode)) {
              uni.showToast({
                title: '请扫描微信付款码（18位数字）',
                icon: 'none'
              });
              return;
            }

            // 2. 调用支付接口
            await handlePayment(payCode);

            // 3. 支付成功后更新状态
            scanStore.setStatus('success');
          } catch (err) {
            // 支付过程中的异常（如接口报错）
            uni.showToast({
              title: `支付失败：${err.message}`,
              icon: 'none'
            });
            scanStore.setStatus('fail');
          } finally {
            isScanning.value = false; // 结束扫码状态
          }
        },
        // 扫码失败（用户取消、相机故障等）
        fail: (err) => {
          uni.showToast({
            title: err.errMsg.includes('cancel') ? '已取消扫码' : '扫码失败',
            icon: 'none'
          });
          scanStore.setStatus('fail');
          isScanning.value = false;
          deleteOrder({
            orderId: orderId.value
          }).then((a) => {})
        }
      });

      uni.hideLoading();
    }

  };

  const handlePayment = async (payCode) => {
    // 显示加载提示
    uni.showLoading({
      title: '支付处理中...',
      mask: true
    });

    try {
      let res1 = await barcodePayment({
        sceneCode: "pickup",
        source: phone.value ? 1 : 2,
        remark: remarks.value,
        orderId: orderId.value,
        phone: phone.value ? phone.value : '',
        authCode: payCode
      })
      if (res1) {
        uni.showToast({
          title: '支付成功！',
          icon: 'success'
        });
        uni.hideLoading();
        remarks.value = ''
        isSearchMode.value = true
        phone.value = ''
        detailList.value = []
        setTimeout(() => {
          const app = getApp();
          app.globalData.switchTabParams = {
            type: 'take'
          };
          uni.switchTab({
            url: '/pages/order/index'
          })

        }, 1000)
      }

    } finally {
      // 无论成功失败，都关闭加载提示
      uni.hideLoading();
    }
  };
  // 确认现金支付
  const surePayment = async () => {
    const cashReceived = cashreceived.value?.trim() || '';

    // 1. 非空校验
    if (!cashReceived) {
      uni.showToast({
        title: '收款金额不能为空',
        icon: 'none',
        duration: 2000
      });
      return; // 校验不通过，阻止提交
    }

    // 2. 格式校验：仅允许整数或两位小数（如100、100.5、100.56）
    const reg = /^\d+(\.\d{1,2})?$/;
    if (!reg.test(cashReceived)) {
      uni.showToast({
        title: '收款金额支持整数或两位小数',
        icon: 'none',
        duration: 2000
      });
      return; // 校验不通过，阻止提交
    }
    let amountPayable = totalPrice.value
    const numValue = Number(cashReceived);
    if (numValue != amountPayable) {
      uni.showToast({
        title: '收款金额与应付金额不一致',
        icon: 'none',
        duration: 2000
      });
      return
    }
    uni.showLoading({
      title: '创建订单中',
      mask: true
    });
    let checked = detailList.value.map(item => {
      return item.cartItemId;
    });
    const res = await createOrder({
      sceneCode: "pickup",
      source: phone.value ? 1 : 2,
      remark: remarks.value,
      cartItemIds: checked,
      userId: userInfo.value.userId
    })
    if (res.Result) {
      let res1 = await purchaseByCash({
        // sceneCode: "pickup",
        // source: 1,
        remark: remarks.value,
        orderId: res.Result,
        merchantRemark: remarksPayment.value
        // phone: phone.value
      })
      if (res1) {
        uni.showToast({
          title: '创建成功！',
          icon: 'success'
        });
        remarks.value = ''
        isSearchMode.value = true
        phone.value = ''
        cashreceived.value = ''
        remarksPayment.value = ''
        detailList.value = []
        showPayment.value = false;
        uni.hideLoading();
        setTimeout(() => {
          const app = getApp();
          app.globalData.switchTabParams = {
            type: 'take'
          };
          uni.switchTab({
            url: '/pages/order/index'
          })
        }, 1000)
      }
    }

  }
</script>
<!-- <style src="./index.scss" lang="scss"></style> -->

<style lang="scss" scoped>
  :deep(.u-number-box__input) {
    height: 22px !important;
    background: #F3F3F3 !important;
    border-radius: 5px;
    line-height: 22px !important;
    min-height: 22px !important;
  }

  .popup-con {
    width: 40vw;
    background: linear-gradient(180deg, #E3F8FF 0%, #FFFFFF 100%);
    box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.04);
    border-radius: 10px;

    .applyfor-tit {
      font-weight: 500;
      font-size: 16px;
      color: #333333;
      text-align: center;
      padding-top: 30px;
      padding-bottom: 17px;
      box-sizing: border-box;
    }

    .applyfor-info {
      margin: 0 30px;

      .applyfor-title {
        font-weight: 500;
        font-size: 20px;
        color: #333;
        margin-bottom: 32px;
        text-align: center;
      }

      .applyfor-item {
        display: flex;
        align-items: center;
        margin-bottom: 18px;

        .applyfor-label {
          min-width: 60px;
          justify-content: flex-end;
          font-weight: 400;
          font-size: 12px;
          color: #333333;
          display: flex;
          align-items: end;
          margin-right: 17px;

          text {
            font-weight: 400;
            font-size: 14px;
            color: #FF5454;
          }
        }
      }

      text {
        font-weight: 400;
        font-size: 14px;
        color: #666666;
        text-align: center;
      }
    }

    .button-group {
      display: flex;
      padding: 0 45px 20px;
      box-sizing: border-box;
      margin-top: 30px;
    }

    .cancel-btn {
      flex: 1;
      height: 40px;
      line-height: 40px;
      background: #EFEFEF;
      border-radius: 21px;
      margin-right: 30rpx;
      font-weight: 400;
      font-size: 14px;
      color: #222222;

      &::after {
        content: " ";
        border: none;
      }
    }

    .pay-btn {
      flex: 1;
      height: 40px;
      line-height: 40px;
      background: #0F90FD;
      border-radius: 21px;
      font-weight: 400;
      font-size: 14px;
      color: #fff;

      &::after {
        content: " ";
        border: none;
      }
    }
  }

  .take-wrapper {
    display: flex;
    flex: 1;
    overflow: hidden;
    margin-top: 10px;

    .empty-box {
      flex: 1;
      align-items: center;
      display: flex;
      justify-content: center;
      flex-direction: column;
      height: 100%;

      .text1 {
        font-weight: 400;
        font-size: 13px;
      }
    }

    .take-left {
      margin-right: 10px;
      height: 100%;
      box-sizing: border-box;
      width: 39%;
      margin-left: 10px;
      display: flex;
      flex-direction: column;

      .member-section {
        background: #FFFFFF;
        border-radius: 8px;
        padding: 10px 10px 18px;
        box-sizing: border-box;
        margin-bottom: 10px;

        .section-title {
          font-weight: 500;
          font-size: 14px;
          color: #0F90FD;
          line-height: 50px;
        }

        /* 内容区通用 */
        .member-content {
          display: flex;
          flex-direction: column;
          background: rgba(15, 144, 253, 0.1);
          padding: 15px 10px;
          box-sizing: border-box;
          border-radius: 8px;
        }

        .dining-row {
          display: flex;
          align-items: center;
          font-weight: 400;
          font-size: 14px;
          color: #666666;
          line-height: 20px;

          :deep(.u-radio__text) {
            font-weight: 400;
            font-size: 14px;
            color: #666666;
          }

          .dining-label {
            margin-right: 8px;
          }
        }

        /* 搜索态 */
        .search-mode {
          .search-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;

            .search-input {
              flex: 1;
              margin-right: 10px;
            }

            .scan-btn {
              display: flex;
              align-items: center;
              background: #FFFFFF;
              padding: 5px 16px;
              border-radius: 30px;
              margin-left: 10px;

              .scan-text {
                margin-left: 7px;
                font-weight: 500;
                font-size: 14px;
                color: #0F90FD;
              }
            }
          }
        }

        /* 结果态 */
        .result-mode {
          position: relative;

          .result-row {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            justify-content: space-between;

            .left-group {
              display: flex;
              align-items: center;
              gap: 10px;

              .avatar {
                width: 40px;
                height: 40px;
                border-radius: 50%;
              }

              .user-text {
                display: flex;
                flex-direction: column;

                .user-name {
                  font-weight: 500;
                  font-size: 14px;
                  color: #333333;
                }

                .user-phone {
                  font-weight: 500;
                  font-size: 14px;
                  color: #333333;
                  margin-top: 4px;
                }
              }
            }

            .right-group {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .member-tag {
                position: absolute;
                top: 0;
                right: 0;
                background: #52C41A;
                border-radius: 0px 10px 0px 10px;
                font-weight: 500;
                font-size: 12px;
                color: #FFFFFF;
                padding: 4px 8px;
                display: inline-flex;
                align-items: center;
                justify-content: center;
              }

              .point-group {
                display: flex;
                align-items: center;
                gap: 4px;
                margin-top: 10px;

                .point-icon {
                  width: 14px;
                  height: 14px;
                }

                .point-text {
                  font-weight: 500;
                  font-size: 14px;
                  color: #FCA236;
                }
              }

              .arrow-icon {
                width: 24px;
                height: 24px;
              }
            }
          }

          .bottom-group {
            display: flex;
            justify-content: space-between;
            align-items: center;

            image {
              width: 16px;
              height: 13px;
            }
          }
        }
      }

      .order-detail-wrapper {
        background-color: #fff;
        border-radius: 10px;
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .selected-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 9px 10px 9px 20px;
          box-sizing: border-box;
          border-bottom: 1px solid rgba(151, 151, 151, 0.16);

          .selected-title {
            font-weight: 500;
            font-size: 14px;
            color: #0F90FD;
          }

          .clear-btn {
            display: flex;
            align-items: center;
            padding: 9px 16px;
            background: #F6F6F6;
            border-radius: 20px;

            .clear-text {
              font-weight: 400;
              font-size: 14px;
              color: #333333;
              margin-left: 3px;
            }
          }
        }


        .goods-container {
          padding: 10px;
          box-sizing: border-box;

          :deep(.u-swipe-action-item) {
            margin-bottom: 10px;
          }

          :deep(.u-swipe-action-item__right__button__wrapper) {
            border-radius: 0 10px 10px 0 !important;
          }

          .combo-item {
            background: #F8F8F8;
            border-radius: 8px;

            .package-title {
              font-weight: 500;
              font-size: 14px;
              color: #000000;
              line-height: 20px;
              padding: 15px 10px;
              box-sizing: border-box;
              border-bottom: 1px solid rgba(151, 151, 151, 0.16);
            }
          }

          /* 商品项整体 */
          .goods-item {
            padding: 17px 10px 14px;
            box-sizing: border-box;
            background: #F8F8F8;
            border-radius: 8px;
          }

          .goods-items {
            padding: 17px 10px 14px;
            box-sizing: border-box;
          }

          .top-row {
            display: flex;
            align-items: center;

            .goods-img {
              width: 60px;
              height: 60px;
              border-radius: 8rpx;
              margin-right: 11px;
              flex-shrink: 0;
            }

            .text-row {
              display: flex;
              flex-direction: column;
              gap: 10px;
              flex: 1;

              .goods-name {
                font-weight: 500;
                font-size: 14px;
                color: #333333;
                line-height: 20px;
              }

              .goods-spec {
                font-weight: 400;
                font-size: 12px;
                color: #999999;
                line-height: 17px;
              }
            }
          }

          .bottom-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 12rpx;

            .price {
              font-weight: 500;
              font-size: 16px;
              color: #333333;
              line-height: 22px
            }

            .quantity-box {
              display: flex;
              align-items: center;

              :deep(.u-number-box__input) {
                width: 31px;
                height: 22px !important;
                background: #FFFFFF !important;
                border-radius: 5px;
                border: 1px solid #DFDFDF;
                line-height: 22px !important;
                min-height: 22px !important;
              }
            }
          }

        }


        .detail-foot {
          width: 100%;
          background: #ffffff;
          box-shadow: 0px -2px 4px 0px rgba(51, 70, 129, 0.1);
          border-radius: 10px;
          height: 54px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: flex-end;
          padding-right: 10px;
          box-sizing: border-box;

          .foot-info {
            font-weight: 400;
            font-size: 14px;
            color: #3A3A3A;
            line-height: 20px;

            text {
              font-weight: 500;
              font-size: 14px;
              color: #F32F1D;
              line-height: 20px;
            }
          }
        }
      }


    }

    .goods-list-wrapper {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .order-search {
        display: flex;
        background-color: #fff;
        margin-bottom: 10px;
        padding: 12px 10px;
        box-sizing: border-box;
        flex-direction: column;
        overflow: hidden;
        border-radius: 8px;
        margin-right: 10px;

        .type-list {
          display: flex;
          flex-direction: row;
          white-space: nowrap;

          .type-item {
            font-weight: 400;
            font-size: 14px;
            color: #666666;
            display: flex;
            align-items: center;
            background: #f6f6f6;
            padding: 7px 12px;
            box-sizing: border-box;
            border-radius: 10px;
            margin-right: 10px;
          }

          .activeType {
            background: rgba(15, 144, 253, 0.1);
            color: #0f90fd;
          }
        }



        :deep(button) {
          width: 74px;
          height: 38px;
          margin-left: 11px;
          margin-right: 0;
          border-radius: 100px;
        }
      }


      .goods-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
        width: 100%;
        padding: 0;
      }

      .goods-item.sold-out {
        opacity: 0.6;
      }

      .goods-item {
        border-radius: 8px;
        background-color: #fff;
        overflow: hidden;
        position: relative;


        /* 状态标签 */
        .status-tag {
          position: absolute;
          top: 0;
          left: 0;
          padding: 2px 10px;
          border-radius: 10px 0px 10px 0px;
          color: #fff;
          font-weight: 500;
          font-size: 12px;
          color: #ffffff;
          line-height: 17px;
          z-index: 2;

          &.off-sale {
            background: #f32f1d;
          }

          &.on-sale {
            background: #52c41a;
          }
        }

        /* 售罄遮罩 */
        .sold-out-mask {
          position: absolute;
          top: 40px;
          left: 0;
          width: 100%;
          // height: calc(100% - 70px);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1;

          image {
            width: 108px;
            height: 108px;
          }
        }

        /* 单选框 */
        .item-check {
          position: absolute;
          top: 10px;
          right: 10px;
          z-index: 3; // 确保在最上层
        }

        /* 商品图片 */
        .goods-img {
          width: 100%;
          height: 160px;
        }

        /* 底部信息区 */
        .goods-info {
          text-align: left;
          padding: 10px;

          .goods-infoi-top {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;

            .goods-name {
              flex: 1;
              font-weight: 500;
              font-size: 14px;
              color: #333333;
              display: block;
              /* 新增：文本溢出处理 */
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .goods-type {
              min-width: 40px;
              position: relative;
              display: inline-block;
              padding: 2px 7px 2px 7px;
              box-sizing: border-box;
              background-color: #5f93f8;
              color: #ffffff;
              font-size: 12px;
              border-radius: 0 4px 4px 0;

              &::after {
                content: '';
                position: absolute;
                top: 0;
                left: -8px;
                width: 0;
                height: 0;
                border-top: 10px solid transparent;
                border-bottom: 10px solid transparent;
                border-right: 8px solid #5f93f8;
              }
            }
          }

          .stock-price {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .stock {
              font-size: 12px;
              color: #0f90fd;
            }

            .price {
              font-size: 14px;
              color: #ff6600;
            }
          }
        }
      }

      .detail-foot {
        margin-top: auto;
        position: static;
        bottom: 0;
        // width: 71vw;
        background: #ffffff;
        box-shadow: 0px -2px 4px 0px rgba(51, 70, 129, 0.1);
        border-radius: 10px;
        height: 54px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px 0 20px;
        box-sizing: border-box;
      }
    }
  }
</style>
